package cn.edu.sdu.sol.intake_system.security.intercepter;

import cn.edu.sdu.sol.intake_system.model.po.SysUser;
import cn.edu.sdu.sol.intake_system.model.po.UserType;
import cn.edu.sdu.sol.intake_system.repository.UserRepository;
import cn.edu.sdu.sol.intake_system.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Optional;

@Component
public class ZAdminInterceptor implements HandlerInterceptor {
    @Autowired
    JwtUtil jwtUtil;

    @Autowired
    UserRepository userRepository;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorizationHeader = request.getHeader("Authorization");
        String token = jwtUtil.extractTokenFromHeader(authorizationHeader);
        String studentNum = jwtUtil.getStudentNumFromToken(token);
        Optional<SysUser> sysUser = userRepository.findUserByStudentNum(studentNum);

        if (sysUser.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            //System.out.println("admin身份验证失败!sysUser.isEmpty()");
            return false;
        }
        SysUser user = sysUser.get();
        if (user.getRole() != UserType.ADMIN && user.getRole() != UserType.SUPER) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            //System.out.println(user.getRole());
            //System.out.println(user.getName());
            //System.out.println(user.getStudentNum());
            //System.out.println("admin身份验证失败!user.getRole() != UserType.ADMIN");
            return false;
        }
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 在处理请求后执行的操作，可留空
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 在完成请求后执行的操作，可留空
    }
}
